import {
  addUser,
  deleteUser,
  updateUser,
  userInfo,
} from '@/services/UserService';
import { User } from '@/types';
import { useModel } from '@@/exports';
import { ModalForm, ProFormRadio, ProFormText } from '@ant-design/pro-form';
import { ActionType, ProColumns, ProTable } from '@ant-design/pro-table';
import { Button, Popconfirm, message } from 'antd';
import { useRef } from 'react';

const UserManager = () => {
  const [_message, contextHolder] = message.useMessage();
  const { peerServer } = useModel('global');
  const ref = useRef<ActionType>();
  const columns: ProColumns<User>[] = [
    {
      title: '昵称',
      dataIndex: 'nickname',
      editable: false,
      width: '200px',
      search: false,
      formItemProps: {
        rules: [
          {
            required: true,
          },
        ],
      },
    },
    {
      title: '用户名',
      dataIndex: 'username',
      editable: false,
      width: '200px',
      search: false,
      formItemProps: {
        rules: [
          {
            required: true,
          },
        ],
      },
    },
    {
      title: '角色',
      dataIndex: 'role',
      width: '100px',
      search: false,
      valueEnum: {
        normal: '普通用户',
        admin: '管理员',
      },
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      valueType: 'dateRange',
      hideInForm: true,
      hideInTable: true,
    },
    {
      dataIndex: 'search',
      editable: false,
      width: '200px',
      hideInForm: true,
      hideInTable: true,
      fieldProps: {
        placeholder: '搜索用户用户名/昵称',
      },
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      valueType: 'dateTime',
      width: '200px',
      search: false,
      formItemProps: {
        rules: [
          {
            required: true,
          },
        ],
      },
    },
    {
      title: '操作',
      valueType: 'option',
      width: '180px',
      render: (text, record, _, action) => [
        <ModalForm<User>
          initialValues={record}
          key="editable"
          width={500}
          title="修改用户"
          trigger={<a>编辑</a>}
          // form={form}
          autoFocusFirstInput
          modalProps={{
            centered: true,
            destroyOnClose: true,
            maskClosable: false,
          }}
          onFinish={async (values) => {
            const { data } = await updateUser(peerServer, values);
            if (data.success) {
              ref.current?.reload(true);
              _message.success('修改成功');
              return true;
            } else {
              _message.error('修改失败');
              return false;
            }
          }}
        >
          <ProFormText name="id" hidden />
          <ProFormText
            name="username"
            label="用户名"
            placeholder="请输入用户名"
            rules={[{ required: true }]}
            disabled
          />
          <ProFormText name="password" label="密码" placeholder="请输入密码" />
          <ProFormText
            name="nickname"
            label="昵称"
            placeholder="请输入昵称"
            rules={[{ required: true }]}
          />
          <ProFormRadio.Group
            name="role"
            label="角色"
            placeholder="请选择角色"
            options={[
              { label: '管理员', value: 'admin' },
              { label: '普通用户', value: 'normal' },
            ]}
            rules={[{ required: true }]}
          />
        </ModalForm>,
        <Popconfirm
          title="确认删除吗？"
          onConfirm={async () => {
            const { data } = await deleteUser(peerServer, record.id);
            if (data.success) {
              ref.current?.reload(true);
              _message.success('删除成功');
            } else {
              _message.error('删除失败');
            }
          }}
        >
          <a key="delete">删除</a>
        </Popconfirm>,
      ],
    },
  ];

  return (
    <div style={{ userSelect: 'none', padding: '20px' }}>
      {contextHolder}
      <ProTable<User>
        style={{ userSelect: 'none' }}
        actionRef={ref}
        size="small"
        rowKey="id"
        headerTitle="用户列表"
        columns={columns}
        options={{
          setting: false,
          density: false,
          reload: true,
        }}
        toolBarRender={() => [
          <ModalForm<User>
            initialValues={{
              role: 'normal',
              password: '123456',
            }}
            width={500}
            title="新建用户"
            trigger={
              <Button key="addUser" type="primary">
                新建用户
              </Button>
            }
            // form={form}
            autoFocusFirstInput
            modalProps={{
              centered: true,
              destroyOnClose: true,
              maskClosable: false,
            }}
            onFinish={async (values) => {
              // console.log(values);
              const { data } = await addUser(peerServer, values);
              if (data.success) {
                ref.current?.reload(true);
                _message.success('提交成功');
                return true;
              } else {
                _message.error('提交失败，住院号重复');
                return false;
              }
            }}
          >
            <ProFormText
              name="username"
              label="用户名"
              placeholder="请输入用户名"
              rules={[{ required: true }]}
            />
            <ProFormText
              name="password"
              label="密码"
              placeholder="请输入密码"
              rules={[{ required: true }]}
            />
            <ProFormRadio.Group
              name="role"
              label="角色"
              placeholder="请选择角色"
              options={[
                { label: '管理员', value: 'admin' },
                { label: '普通用户', value: 'normal' },
              ]}
              rules={[{ required: true }]}
            />
            <ProFormText
              name="nickname"
              label="昵称"
              placeholder="请输入昵称"
              rules={[{ required: true }]}
            />
          </ModalForm>,
        ]}
        request={async (params) => {
          // console.log(params);
          try {
            const { data } = await userInfo(peerServer, {
              page: params.current as number,
              size: params.pageSize as number,
              createTime: params.createTime,
              search: params.search,
            });
            return {
              success: data.success,
              data: data.data.items,
              total: data.data.count,
            };
          } catch {
            _message.error('连接服务器失败');
            return {
              success: false,
            };
          }
        }}
        pagination={{ pageSize: 10 }}
      />
    </div>
  );
};

export default UserManager;
